/*
 * this is the new final version of the csvdb file .
 * I have made some changes in the column file as well.
 * I added the attribute to column structure called relatioName, and set it in scanfile method.
 * I have added the functionality to do join oon conditions R.B=S.D.
 * I also checked in the condition if they are given in reverse order, i.e.
 * it will work in both these conditions.
 * U=Join(R,S,R.B=S.D) and
 *  U=Join(R,S,S.D=R.B).

 */
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.*;
import java.io.*;

public class csvdb {
	static String inputfile,outputfile,method,arg;
	static String outputRelation ="";
	static String inputRelation ="";
	
	public static void main(String[] args) {
		String[] cols = new String[20];
		if(args.length<1)
			System.out.print("Arguments Missing!!!\n. Please provide some query to process.");
		else 
			{
				if(args.length>1)
				System.out.print("More Than Required Arguments. Check Syntax.!!!\n");
			    int cmdType = findCmd(args[0]);
				if(cmdType==0)
					System.out.print("Error in Input Command. please check again!!!");
				if(cmdType==1){
					extractDisplayComponents(args[0]);
				    column R = scanfile(outputRelation);
				    for (int i =0; i<R.sizeofcolumn();i++)
				    {
				    	System.out.printf("%14s", R.getcolumn(i).getname());
				    }
				    System.out.print("\n");
				    for(int row=0;row<R.sizeofchild();row++)
				    {
				    	for (int colnum=0; colnum<R.sizeofcolumn();colnum++ ){
				    		String temp = R.getcolumn(colnum).getchild(row);
				    		if (temp!=null&&temp.equals("")){
				    			System.out.printf("      NULL");
				    		}else{
				    			temp = R.getcolumn(colnum).getchild(row);
				    			if (temp.length()>=12){
				    				temp = temp.substring(0, 12);
				    			}
				    			System.out.printf("%14s", temp);
				    		}				    		
				    	}
				    	System.out.print("\n");
				    }
				    
				}
					
				if(cmdType==2)
					extractSelectComponents(args[0]);
				if(cmdType==4)
				{
				extractJoinComponents(args[0]);
				}
				if(cmdType==3){
					cols = extractProjectComponents(args[0]);
					column R = scanfile(inputRelation);
					//column S = new column();
					BufferedWriter out = openforwrite(outputRelation);
				    int i=0;
				    while(cols[i]!=null){
				    	i++;
				    }
				    try{
					    if (i>=1){
					    	int[] index = new int[i];
					    	for(int k=0; k<i; k++){
					    		index[k] = R.indexofcolumn(cols[k]);
					    		if (index[k] ==-1){
							    	System.out.print("No column named "+cols[k]+" for projecting, Exit!");
							    	System.exit(1);
					    		}				    		
					    	}//end for
					    	//S.setname(cols[0]);
					    	out.write(cols[0]);
					    	for (int k=1; k<i; k++){
					    		//S.addsibling(cols[k]);
					    		out.write(","+cols[k]);
					    	}
					    	out.write("\n");				    	
					    	for (int k=0; k<R.sizeofchild();k++){
					    		if(!R.existuple(k, index)){
					    			out.write(R.getcolumn(index[0]).getchild(k));
						    		for (int j=1; j<i; j++){
							    		out.write(","+R.getcolumn(index[j]).getchild(k));
							    	}
						    		out.write("\n"); 
					    		}
					    	}
					    	out.close();
					    	
					    }else{
					    	System.out.print("No column to Project, Exit!");
					    	System.exit(1);
					    }
				    }catch (IOException ioe)
					  {
						  System.err.println(ioe);
					  }
					
				}//end if(cmdType==3)				
			}
		System.exit(0);
	}
	
	private static int findCmd(String cmd)
	{
		
		int returnVal=0;
		String token="";
		String regex = "\\s*[Dd][Ii][Ss][Pp][Ll][Aa][Yy]\\s*\\(\\w+\\)\\s*";
		String regex1="\\s*\\w+\\s*\\=\\s*[Ss][Ee][Ll][Ee][Cc][Tt]\\s*\\(";
		String regex2="\\s*\\w+\\s*\\=\\s*[Pp][Rr][Oo][Jj][Ee][Cc][Tt]\\s*\\(";Pattern p =Pattern.compile(regex);
		String regex3 = "\\s*\\w+\\s*\\=\\s*[Jj][Oo][Ii][Nn]\\s*\\(";
		Matcher m = p.matcher(cmd); 
		if (m.find()) 
	      {
	    	token=m.group();
	    	returnVal= 1;
		}
		p =Pattern.compile(regex1);
		m = p.matcher(cmd); 
		if (m.find()) 
	      {
	    	token=m.group();
	    	returnVal= 2;
		}
		p =Pattern.compile(regex2);
		m = p.matcher(cmd); 
		if (m.find()) 
	      {
	    	token=m.group();
	    	returnVal= 3;
		}
		p =Pattern.compile(regex3);
		m = p.matcher(cmd); 
		if (m.find()) 
	      {
	    	token=m.group();
	    	returnVal= 4;
		}
		
	return returnVal;
	}
	private static void extractDisplayComponents(String cmd)
	{
		boolean flag = false;
		outputRelation ="";
		int index=0;
		char[] output = new char[50];
		
		//find components for display statements.
		for(int i=0;i<cmd.length();i++)
		  {
				if(flag)
			    {
				  if(cmd.charAt(i)==')')
					break;
				  else
					{
					  output[index]=cmd.charAt(i);
					  System.out.print("output["+index+"] :  "+output[index]+"\n");
					  index++;
					}
			    }
				if(cmd.charAt(i)=='(')
				flag=true;
		    
		}
			outputRelation = new String (output);
			outputRelation = outputRelation.toLowerCase().trim();
	        
	}

	private static void extractSelectComponents(String cmd)
	{
		boolean flag = false;
		boolean attrStart = false;
		boolean inputdetected=false;
		String outputRelation ="";
		String inputRelation ="";
		String condition ="";
		int index=0, cond_index=0;
		char[] output = new char[50];
		char[] input = new char[50];
		char[] cond = new char[50];
		
		
		//find components for select statements.
		for(int i=0;i<cmd.length();i++)
		  {
				if(cmd.charAt(i)=='='&& !flag)
					{
					flag=true;
					outputRelation = new String (output); 
					if(outputRelation.charAt(0)=='"')
						outputRelation = (outputRelation.substring(1,outputRelation.length())).trim();
						outputRelation = outputRelation.toLowerCase();}
				else 
					{
					output[index]=cmd.charAt(i);
					index++;
					}
				if(attrStart)
				{
					if(!inputdetected)
					{
						if(cmd.charAt(i)==',')
						{
							inputRelation = new String (input);
							inputRelation= inputRelation.toLowerCase().trim();
							
						inputdetected=true;
						}
						else
							{
							input[index]=cmd.charAt(i);
							index++;
							}
					}
					else
						if(cmd.charAt(i)==')')
						{
							condition = new String (cond);
						}
						else
							{
							cond[cond_index]=cmd.charAt(i);
							cond_index++;
							}
					}
				if(cmd.charAt(i)=='('&&flag)
					{
					attrStart=true;
					index=0;
					}
				if(cmd.charAt(i)==')'&&attrStart)
					break;
				
					
				}
		column res = scanfile(inputRelation.trim());
		select(res,outputRelation.trim(),condition);
		  }
	private static void extractJoinComponents(String cmd)
	{
		boolean flag = false;
		boolean attrStart = false;
		String outputRelation ="";
		String inputRelation1 ="";
		String inputRelation2 ="";
		String joinCol="";
		int index=0;
		boolean relationOneFound=false;
		char[] output = new char[50];
		//find components for Join statements.
		for(int i=0;i<cmd.length();i++)
		  {
				if(cmd.charAt(i)=='='&& !flag)
					{
					flag=true;
					outputRelation = new String (output); 
					if(outputRelation.charAt(0)=='"')
						outputRelation = (outputRelation.substring(1,outputRelation.length())).trim();
						outputRelation = outputRelation.toLowerCase().trim();}
				else {
					if(!flag)
				     {
					output[index]=cmd.charAt(i);
					index++;
					}
					}
				if(attrStart)
				{
					String regex = "\\s*\\w+\\s*\\,";
					Pattern p =Pattern.compile(regex);
					Matcher m = p.matcher(cmd); 
					while (m.find()) 
				      {
				    	
						if(relationOneFound)
							inputRelation2=m.group().substring(0,m.group().length()-1);
				    	else {
				    		inputRelation1=m.group().substring(0,m.group().length()-1);
				    		relationOneFound=true;
						}
				    	
					}
					regex = "\\s*\\w+\\s*\\)|\\s*\\w+\\s*=\\s*\\w+\\s*\\)|\\s*\\w+\\.\\w+\\s*=\\s*\\w+\\.\\w+\\s*\\)";
					p =Pattern.compile(regex);
					m = p.matcher(cmd); 
					if (m.find()) 
				      {
				    	joinCol=m.group().substring(0,m.group().length()-1);
				      }
				}	
				if(cmd.charAt(i)=='('&&flag)
					{
					attrStart=true;
					
					}
				if(cmd.charAt(i)==')'&&attrStart)
					{
					
					break;
					}
				
					
				}
		column inputRel1 = scanfile(inputRelation1.trim());
		column inputRel2 = scanfile(inputRelation2.trim());
		if(joinCol.indexOf("=")<0){
			join(inputRel1, inputRel2, outputRelation, joinCol);	
		}else{
			EquiJoin(inputRel1, inputRel2, outputRelation, joinCol);
		}
		
		 }
	
	private static String[] extractProjectComponents(String cmd)
	{
		boolean flag = false;
		boolean attrStart = false;
		boolean colStart=false;
		
		String[] cols = new String[100];
		int index=0, cond_index=0;
		char[] output = new char[50];
		for(int i=0;i<cmd.length();i++)
		  {
			
				if(cmd.charAt(i)=='=')
					{
					flag=true;
					outputRelation = new String (output);
					if(outputRelation.charAt(0)=='"')
						outputRelation = (outputRelation.substring(1,outputRelation.length())).trim();
					outputRelation = outputRelation.toLowerCase();
			        }
				else 
					{
					if(!flag)
					{
					output[index]=cmd.charAt(i);
					index++;
					
					}
					}
				if(cmd.charAt(i)==')'&&attrStart)
					break;
				
				if(cmd.charAt(i)=='('&&flag)
					{
					attrStart=true;
					index=0;
					}
				if(attrStart)
				{
					String regex="\\s*\\w+\\s*,|\\s*\\w+\\s*\\)";
						Pattern p =Pattern.compile(regex);
						Matcher m = p.matcher(cmd); 
						while(m.find())
						{
							String token=m.group();
							if(!colStart)
							{
								inputRelation= token.substring(0,token.length()-1).toLowerCase().trim();
								colStart=true;
								i=i+token.length();
							}
							else
							{
								cols[cond_index]=token.substring(0,token.length()-1);
								cond_index++;
								i=i+token.length();
							}
						}
						
					}
				
				
				}
		return cols;
	}
	
	
	public static column scanfile(String file)
	{
		column R = new column();
		String regex_name = "[A-Za-z]{1}\\w*|\"[\\w, ]*\"";
		String regex_number ="\\t?|[+|-]?[0-9]+|[+|-]?[0-9]+.[0-9]+|[+|-]?[0-9]+.?[0-9]*[e|E][-|+]?[0-9]+";
		
		try{
		    if (file == null)
		    	throw new IOException();
		    R.relationName=file;
			BufferedReader in= new BufferedReader(new FileReader(file.trim()+".csv"));
			String line =new String();
			if (((line =in.readLine())==null)){
				System.out.print("Wrong Column Name. Please check the input file\n");
				System.exit(1);
			}
			line= line.trim();
            int prt = 0, flag=0;
            String[] s0 = line.split(",");
            Pattern pattern_name = Pattern.compile(regex_name);
            Pattern pattern_num  = Pattern.compile(regex_number);
            
            for (int i=0;i<s0.length;i++){
		    	s0[i] = s0[i].trim();		    	
		    	Matcher matcher = pattern_name.matcher(s0[i]);		    	
		    	if(!matcher.matches()){
		    		System.out.print(line+"---Wrong Column, exit\n");
			    	System.exit(1);;
		    	}	    		
		    	//if (s0[i].equals("")) {		    		
		    	//	System.out.print(line+"Wrong Column, exit\n");
			    //	System.exit(1);;
		    	//}
		    }
            for (int i=0;i<s0.length;i++){
		    	if (i == 0) {
		    		R.setname(s0[i]);
		    	}else{
		    		if (R.indexofcolumn(s0[i]) >=0){
		    			System.out.print(line+"---Wrong Column, exit\n");
				    	System.exit(1);;
		    		}
		    		R.addsibling(new column(s0[i]));
		    	}		    	
		    }
            
            int line_num = 1;
            
			while ((line=in.readLine())!=null){
				line =line.trim();
				prt = 0;
				String[] s1;
				int num = R.sizeofcolumn();
				if (line.endsWith(",")) {
					line = line.concat("0");
					s1 = line.split(",");
					s1[s1.length-1]="";
				}else{
					s1= line.split(",");
				}	
				
			    int n = s1.length;
			    /* begin check whether , is in ""*/
			    for (int i =0;i< n;i++){
			    	if (s1[i].startsWith("\"")){
			    		for (int j=i+1; j<n;j++){
			    			s1[i] = s1[i].concat(","+s1[j]);
			    			if(s1[j].endsWith("\"")){
			    				//s1[i] = s1[i].concat(","+s1[j]);
			    				for (int k=i+1; k<n-(j-i);k++){
			    					s1[k] = s1[k+j-i];	
			    				}
			    				n = n-(j-i);
			    				break;
			    			}
			    		}//end for
			    	}
			    }
			    // end check and proceed the , in ""
			    if (n!= num){
			    	System.out.print("Line"+line_num+":\""+line+"\""+"--Data of this line are wrong, skipping\n");
			    	line_num++;
			    	continue;
			    }
			    flag = 0;
	            for (int i=0;i<n;i++){
			    	s1[i] = s1[i].trim();		    	
			    	Matcher matcher_name = pattern_name.matcher(s1[i]);
			    	Matcher matcher_num  = pattern_num.matcher(s1[i]);
			    	if(matcher_name.matches()){
			    		R.getcolumn(i).type_total++;
			    	}else if (matcher_num.matches()){
			    		R.getcolumn(i).type_total--;
			    	}else{
			    		flag = 1;
			    	}			    		
	            }//end for
	            if (flag ==1){	            	
	            	System.out.print("Line"+line_num+":\""+line+"\""+"--Data of this line are wrong, skipping\n");
	            	line_num++;
	            	continue;
	            }
	            if (s1[0].equals("")){
	            	System.out.print("Line"+line_num+":\""+line+"\""+"--PK can't be null, skipping\n");
	            	line_num++;
	            	continue;
	            }
	            if (R.indexofchild(s1[0], 1)>=0){
	            	System.out.print("Line"+line_num+":\""+line+"\""+"--Duplicate PK, skipping\n");
	            	line_num++;
	            	continue;
	            }else{
	            	R.getcolumn(0).addchild(s1[0]);
	            }
			    for (int ss=1;ss<n;ss++){
			    	//R.getcolumn(ss).addchild(Double.valueOf(s1[ss]));
			    	R.getcolumn(ss).addchild(s1[ss]);			    	
			    }
			    line_num++;
			}//end while	
			for( int i=0; i<R.sizeofcolumn();i++){
				if (R.getcolumn(i).type_total>=0){
					R.getcolumn(i).settype("string");
				}else{
					R.getcolumn(i).settype("float");
				}
			}
			
						    
		}catch(FileNotFoundException fnfe)
		  	{
			  System.err.println(fnfe);
			  }
		catch(IOException ioe)
			  {
			  System.err.println(ioe);
			  }
		//R.sizeofchild();
		//R.sizeofcolumn();
		return R;
}


public static BufferedWriter openforwrite(String s){
    BufferedWriter out = null;
    try{
	    if (s == null)
	    	throw new IOException();	   
	    out= new BufferedWriter(new FileWriter(s.trim().concat(".csv")));
	   
	}// end try
    catch(IOException ioe)
	  {
	  System.err.println(ioe);
	  }
    return out;	
}
private static void select(column input, String output, String cond){
	boolean flag=false, isFloat=false,iscolumn=false;
	int splitindex =extractCondOperators(cond);
	String opnd1=cond.substring(0, splitindex);
	String opnd2=cond.substring(splitindex+1, cond.length()).trim();
	char op = cond.charAt(splitindex);
	//String p =opnd1;
	int n1 = input.indexofcolumn(opnd1);
	int n2 = input.indexofcolumn(opnd2);
	try{
	BufferedWriter out = new BufferedWriter(new FileWriter(output+".csv"));
    if(n1<0)
		{
		System.exit(1);
		}
    if(n2>0)
   {
	   if(!(input.getcolumn(n1).gettype().equals(input.getcolumn(n1).gettype())))
	   {
		   System.out.print("The types of the two columns don't match.\n");
		   System.exit(1);
	   }
	   else 
		   iscolumn=true;
   }
    if(n2<0)
        {
    	if(!(input.getcolumn(n1).gettype().equals(getCondType(opnd2))))
    {
    	System.out.print("The type of the condition arguments don't match.\n");
    	System.exit(1);
    }
    if(getCondType(opnd2).equals("float"))
    	isFloat=true;
        }	
    for(int i=0;i<input.sizeofcolumn();i++)
		{
		if(i<input.sizeofcolumn()-1)
		{
			out.write(input.getcolumn(i).getname()+",");	
		}
		else
		{
			out.write(input.getcolumn(i).getname());
			out.newLine();
		}
		}
	for(int i=0;i<input.sizeofchild();i++)
	{
		switch(op)
		{
		case '=' : 
			if(iscolumn)
			{
				if(input.getcolumn(n1).gettype().equals("string"))
					{
					if(input.getcolumn(n1).getchild(i).equals(input.getcolumn(n2).getchild(i)))
					{
						flag=true;
					   }
					}
				else
					{
					if(input.getcolumn(n1).getchildfloat(i)==input.getcolumn(n2).getchildfloat(i))
						{
						flag=true;
		                }
					}
			}
		else
		{
			if(isFloat)
			{
				float f = Float.valueOf(opnd2.trim()).floatValue();
                if(!input.getcolumn(n1).getchild(i).equals("")&&(input.getcolumn(n1).getchildfloat(i)==f))
			    {
                	flag=true;
                	}
				}
		   else
		   {
			   if(!input.getcolumn(n1).getchild(i).equals("")&&(input.getcolumn(n1).getchild(i).equals(opnd2)))
				{
		    	   flag=true;
				}
			}
		}
		if(flag)
		{
			for(int j=0; j<input.sizeofcolumn();j++)
			{
			String a=input.getcolumn(j).getchild(i);
			if(j==input.sizeofcolumn()-1)
				{
				out.write(a+"\n");
				out.newLine();
				flag=false;
				}
			else
				{
			out.write(a+",");
			flag=false;
			    }
			}
		}
		break;
		case '<' : 
			if(iscolumn)
			{
				if(input.getcolumn(n1).gettype().equals("string"))
				{
				System.out.print("operation < is not applicable on strings data type.\n");
				System.exit(1);
				}
			else
				if(input.getcolumn(n1).getchildfloat(i)<input.getcolumn(n2).getchildfloat(i))
					flag=true;
			}
		else
		{
			if(isFloat)
			{
				float f = Float.valueOf(opnd2.trim()).floatValue();
				if(!input.getcolumn(n1).getchild(i).equals("")&&input.getcolumn(n1).getchildfloat(i)<f)
					flag=true;
	        }
			else
			{
			System.out.print("The operation < is not applicable on strings.\n");
			System.exit(1);
		    }
	  }
		if(flag)
		{
			for(int j=0; j<input.sizeofcolumn();j++)
			{
			String a=input.getcolumn(j).getchild(i);
			if(j==input.sizeofcolumn()-1)
			{
				out.write(a);
				out.newLine();
				flag=false;
				}
			else
			{
			out.write(a+",");
			flag=false;
			}
			}}
		break;
		case '>' :  if(iscolumn)
		{
			if(input.getcolumn(n1).gettype().equals("string"))
			{
			System.out.print("operation < is not applicable on strings data type.\n");
			System.exit(1);
			}
		else
			if(input.getcolumn(n1).getchildfloat(i)>input.getcolumn(n2).getchildfloat(i))
				flag=true;
		}
	else
	{
		if(isFloat)
		{
			float f = Float.valueOf(opnd2.trim()).floatValue();
			if(!input.getcolumn(n1).getchild(i).equals("")&&input.getcolumn(n1).getchildfloat(i)>f)
				flag=true;
        }
		else
		{
		System.out.print("The operation > is not applicable on strings.\n");
		System.exit(1);
	    }
  }
	if(flag)
	{
		for(int j=0; j<input.sizeofcolumn();j++)
		{
		String a=input.getcolumn(j).getchild(i);
		if(j==input.sizeofcolumn()-1)
		{
			out.write(a);
			out.newLine();
			flag=false;
			}
		else
		{
		out.write(a+",");
		flag=false;
		}
		}}
	break;
		default: System.out.print("Operator unknown");
		break;
		}
	}
	out.close();
	}
	catch (Exception e)
	 {
		 //Catch exception if any
	     System.err.println("Error: " + e.getMessage());
	 }
	
}
private static void join(column inputRelation1, column inputRelation2, String outputRelation, String joinCol)
{
	int n1 = inputRelation1.indexofcolumn(joinCol);
	int n2 = inputRelation2.indexofcolumn(joinCol);
	String a="";
	if(n1<0||n2<0)
	{
		System.out.print("The column doesn't exist in both the relations.\n");
		System.exit(1);
	}
	if(!inputRelation1.getcolumn(n1).gettype().equals(inputRelation2.getcolumn(n2).gettype()))
	{
		System.out.print("type didn't matched\n");
		System.exit(1);
	}
	try{
		BufferedWriter out = new BufferedWriter(new FileWriter(outputRelation+".csv"));
		for(int i=0;i<inputRelation1.sizeofcolumn();i++)
		{
			if(!inputRelation1.getcolumn(i).getname().equals(joinCol))
			out.write(inputRelation1.getcolumn(i).getname()+",");	
		
		}
		for(int i=0;i<inputRelation2.sizeofcolumn();i++)
		{
		
			if(i<inputRelation2.sizeofcolumn()-1)
		{
			out.write(inputRelation2.getcolumn(i).getname()+",");	
		}
		else
		{
			out.write(inputRelation2.getcolumn(i).getname());
			out.newLine();
		}
		}
		for(int i=0;i<inputRelation1.sizeofchild();i++)
		{
			for(int j=0;j<inputRelation2.sizeofchild();j++)
			{
				boolean flag=false;
				if(inputRelation1.getcolumn(n1).gettype().equals("string"))
				{
					if(inputRelation1.getcolumn(n1).getchild(i).equals(inputRelation2.getcolumn(n2).getchild(j)))
						flag=true;
				}
				else
				{
					if(inputRelation1.getcolumn(n1).getchildfloat(i)==inputRelation2.getcolumn(n2).getchildfloat(j))
						flag=true;
				}
				if(flag)
						{
					for(int x=0; x<inputRelation1.sizeofcolumn();x++)
					{
						if(!inputRelation1.getcolumn(x).getname().equals(joinCol))
						{
							a=inputRelation1.getcolumn(x).getchild(i);
							out.write(a+",");
						}
						
					}
					for(int y=0; y<inputRelation2.sizeofcolumn();y++)
					{
						a=inputRelation2.getcolumn(y).getchild(j);
						if(y==inputRelation2.sizeofcolumn()-1)
						{
							out.write(a);
							out.newLine();
							
							}
						else
						{
						out.write(a+",");
			    		
						}
					}
						}// end if(flag)
				flag = false;
			}
		}
		out.close();
}catch (Exception e)
{
	 //Catch exception if any
    System.err.println("Error: " + e.getMessage());
}
}

private static void EquiJoin(column inputRelation1, column inputRelation2, String outputRelation, String joinCond)
{
	int n1=0,n2=0;
	boolean flag=false;
	int splitindex =extractCondOperators(joinCond);
	char op = joinCond.charAt(splitindex);
    if(!(op=='='))
    {
    	System.out.print("An EquiJoin command cannot have any other operator other than = .\n");
    	System.exit(1);
    }
    String opnd1=joinCond.substring(0, splitindex).trim();
	String opnd2=joinCond.substring(splitindex+1, joinCond.length()).trim();
	if(checkRelationSpecified(joinCond))
	{
		int pos1=0,pos2=0;
	    String relation1="",relation2="";
		pos1=extractEquiJoinOperandPosition(opnd1);
		pos2=extractEquiJoinOperandPosition(opnd2);
		relation1=opnd1.substring(0, pos1);
		relation2=opnd2.substring(0, pos2);
		if(relation1.equals(inputRelation1.relationName)&&relation2.equals(inputRelation2.relationName))
		{
			opnd1=opnd1.substring(pos1+1, opnd1.length()).trim();
			opnd2=opnd2.substring(pos2+1, opnd2.length()).trim();
			n1 = inputRelation1.indexofcolumn(opnd1);
			n2 = inputRelation2.indexofcolumn(opnd2);
		}
		if(relation1.equals(inputRelation2.relationName)&&relation2.equals(inputRelation1.relationName))
		{
			opnd1=opnd1.substring(pos1+1, opnd1.length()).trim();
			opnd2=opnd2.substring(pos2+1, opnd2.length()).trim();
			n1 = inputRelation1.indexofcolumn(opnd2);
			n2 = inputRelation2.indexofcolumn(opnd1);
		}
		
	}
	else
	{
	n1 = inputRelation1.indexofcolumn(opnd1);
	n2 = inputRelation2.indexofcolumn(opnd2);
	}
	String a="";
	if(n1<0||n2<0)
	{
		System.out.print("The columns doesn't exist in both the relations.\n");
		System.exit(1);
	}
	if(!inputRelation1.getcolumn(n1).gettype().equals(inputRelation2.getcolumn(n2).gettype()))
	{
		System.out.print("type didn't matched\n");
		System.exit(1);
	}
	try{
		BufferedWriter out = new BufferedWriter(new FileWriter(outputRelation+".csv"));
		for(int i=0;i<inputRelation1.sizeofcolumn();i++)
		{
			out.write(inputRelation1.getcolumn(i).getname()+",");	
		
		}
		for(int i=0;i<inputRelation2.sizeofcolumn();i++)
		{
		
			if(i<inputRelation2.sizeofcolumn()-1)
		{
			out.write(inputRelation2.getcolumn(i).getname()+",");	
		}
		else
		{
			out.write(inputRelation2.getcolumn(i).getname());
			out.newLine();
		}
		}
		for(int i=0;i<inputRelation1.sizeofchild();i++)
		{
			for(int j=0;j<inputRelation2.sizeofchild();j++)
			{
				if(inputRelation1.getcolumn(n1).gettype().equals("string"))
				{
					if(inputRelation1.getcolumn(n1).getchild(i).equals(inputRelation2.getcolumn(n2).getchild(j)))
						flag=true;
				}
				else
				{
					if(inputRelation1.getcolumn(n1).getchildfloat(i)==inputRelation2.getcolumn(n2).getchildfloat(j))
						flag=true;
				}
				if(flag)
						{
					for(int x=0; x<inputRelation1.sizeofcolumn();x++)
					{
						
							a=inputRelation1.getcolumn(x).getchild(i);
							out.write(a+",");
												
					}
					for(int y=0; y<inputRelation2.sizeofcolumn();y++)
					{
						a=inputRelation2.getcolumn(y).getchild(j);
						if(y==inputRelation2.sizeofcolumn()-1)
						{
							out.write(a);
							out.newLine();
							flag=false;
							}
						else
						{
						out.write(a+",");
			    		flag=false;
						}
					}
						}
			}
		}
		out.close();
}catch (Exception e)
{
	 //Catch exception if any
    System.err.println("Error: " + e.getMessage());
}
}
private static int extractCondOperators(String cond)
{
	int index=0;
	if(cond.contains("="))
	index=cond.indexOf('=');
	if(cond.contains("<"))
		index=cond.indexOf('<');
	if(cond.contains(">"))
		index=cond.indexOf('>');
	return index;
	
}
private static String getCondType(String opnd2)
{
	String curr_type="";
	String regex1="\\s*\\w+\\s*";
	String regex2="[1-9]+[0-9]*";
	Pattern p =Pattern.compile(regex1);
	Matcher m = p.matcher(opnd2); 
	if(m.find())
	curr_type="string";
	p =Pattern.compile(regex2);
	m = p.matcher(opnd2); 
	if(m.find())
	curr_type="float";
	return curr_type;
}
private static boolean checkRelationSpecified(String joinCond)
{
	String regex1="\\s*\\w+\\.\\w+\\s*=\\s*\\w+\\.\\w+\\s*";
	Pattern p =Pattern.compile(regex1);
	Matcher m = p.matcher(joinCond); 
	if(m.find())
		return true;
	else 
		return false;
	
}
private static int extractEquiJoinOperandPosition(String opnd)
{
	int index=0;
	if(opnd.contains("."))
	index=opnd.indexOf('.');
	return index;
}

}

